<?php

namespace app\controllers;

use app\lib\AppController;
use app\lib\WXBizDataCrypt;
use Yii;

class LoginController extends AppController
{
    public function actionIndex(){

    }
    public function actionLogin()
    {
        // 接收参数
        $data = $_GET;
        //echo json_encode($data);
        //引入解密文件 在微信小程序开发文档下载
        $appid = "wx94867464590fecb7";
        $appsecret = "bd0392bdb8d061925bba2bca7824c0da";
        $grant_type = "authorization_code"; //授权（必填）
        $code = $data['code'];    //有效期5分钟 登录会话
        $encryptedData=urldecode($data['encryptedData']);
        //echo json_encode($encryptedData);
        $iv = urldecode($data['iv']);
        //echo json_encode($iv);
        $signature = $data['signature'];
        $rawData = $data['rawData'];

        // 拼接url
        $url = "https://api.weixin.qq.com/sns/jscode2session?"."appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=".$grant_type;
        $res = json_decode($this->httpGet($url),true);
        $sessionKey = $res['session_key']; //取出json里对应的值
        $signature2 = sha1(htmlspecialchars_decode($rawData).$sessionKey);

        // 验证签名
        if ($signature2 !== $signature){
            echo json_encode("验签失败");
        }
        // 获取解密后的数据
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0) {
            echo json_encode($data);
        } else {
            echo json_encode($errCode);
        }
    }

    public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
}
